package com.sznaner.tool.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AssetsFileUtil {

    private static AssetsFileUtil instance;
    private static final int SUCCESS = 1;
    private static final int FAILED = 0;
    private FileOperateCallback callback;
    private volatile boolean isSuccess;
    private String errorStr;

    public static AssetsFileUtil getInstance() {
        if (instance == null)
            instance = new AssetsFileUtil();
        return instance;
    }

    private AssetsFileUtil() {
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (callback != null) {
                if (msg.what == SUCCESS) {
                    callback.onSuccess();
                }
                if (msg.what == FAILED) {
                    callback.onFailed(msg.obj.toString());
                }
            }
        }
    };

    public AssetsFileUtil copyAssetsToSD(final String formFloder, final String toFloder) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                copyAssetsToDst(formFloder, toFloder);
                if (isSuccess)
                    handler.obtainMessage(SUCCESS).sendToTarget();
                else
                    handler.obtainMessage(FAILED, errorStr).sendToTarget();
            }
        }).start();
        return this;
    }

    public void setFileOperateCallback(FileOperateCallback callback) {
        this.callback = callback;
    }

    private void copyAssetsToDst(String formFloder, String toFloder) {

        Context context = NRTool.context();
        try {
            String fileNames[] = context.getAssets().list(formFloder);
            if (fileNames.length > 0) {
                //File file = new File(Environment.getExternalStorageDirectory(), dstPath);
                File file = new File(context.getExternalFilesDir(null).getAbsolutePath(), toFloder);
                if (!file.exists()) file.mkdirs();
                for (String fileName : fileNames) {
                    if (!formFloder.equals("")) { // assets 文件夹下的目录
                        copyAssetsToDst(formFloder + File.separator + fileName, toFloder + File.separator + fileName);
                    } else { // assets 文件夹
                        copyAssetsToDst(fileName, toFloder + File.separator + fileName);
                    }
                }
            } else {
                //File outFile = new File(Environment.getExternalStorageDirectory(), toFloder);
                File outFile = new File(context.getExternalFilesDir(null).getAbsolutePath(), toFloder);
                InputStream is = context.getAssets().open(formFloder);
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            errorStr = e.getMessage();
            isSuccess = false;
        }
    }

    /**
     * 将asset文件写入缓存
     */public static boolean copyAssetAndWrite(Context context, String fileName){
        try {
            File cacheDir=context.getCacheDir();
            if (!cacheDir.exists()){
                cacheDir.mkdirs();
            }
            File outFile =new File(cacheDir,fileName);
            if (!outFile.exists()){
                boolean res=outFile.createNewFile();
                if (!res){
                    return false;
                }
            }else {
                if (outFile.length()>10){//表示已经写入一次
                    return true;
                }
            }
            InputStream is= context.getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }    return false;
    }

    public static String getAssetFile(Context context, String fileName){
        File dataFile=new File(context.getCacheDir(),fileName);
        return dataFile.getAbsolutePath();
    }

    public interface FileOperateCallback {
        void onSuccess();

        void onFailed(String error);
    }

}